package com.navinfo.opentsp.platform.computing.serializer;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Charsets;
import com.navinfo.opentsp.platform.computing.dto.FaultInfoDto;
import com.navinfo.opentsp.platform.location.protocol.common.LCFaultInfo;
import com.navinfo.opentsp.platform.computing.util.DateUtils;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.serialization.EventSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * OF39故障信息
 * HDFS_Sink的FaultInfo序列化器，拼接成字段间通过\001分割的字符串
 */
public class HDFSFaultInfoSerializer implements EventSerializer {
    private static final Logger logger = LoggerFactory.getLogger(HDFSFaultInfoSerializer.class);

    private final String APPEND_NEWLINE = "appendNewline";
    private final boolean appendNewline;
    private final String splitStr = "\001";
    private final OutputStream out;

    private HDFSFaultInfoSerializer(OutputStream out, Context ctx) {
        this.appendNewline = ctx.getBoolean(APPEND_NEWLINE, true);
        this.out = out;
    }

    public boolean supportsReopen() {
        return false;
    }

    public void afterCreate() {
    }

    public void afterReopen() {
    }

    public void beforeClose() {
    }

    public void flush() throws IOException {
        this.out.flush();
    }

    public void write(Event event) throws IOException {
        try {
            //拼写落盘到HDFS的字符串。字段间分隔符是\001，null通过\N表示
            LCFaultInfo.FaultInfo faultInfo = LCFaultInfo.FaultInfo.parseFrom(event.getBody());
            LCFaultInfo.GpsLocationData gpsLocationData = faultInfo.getGpsLocationData();

            StringBuilder faultInfoStr = new StringBuilder(5000);
            faultInfoStr
                    .append(faultInfo.getTerminalId()).append(splitStr)
                    .append(gpsLocationData.getGpsTime()).append(splitStr)
                    .append(gpsLocationData.getLongitude()).append(splitStr)
                    .append(gpsLocationData.getLatitude()).append(splitStr)
                    .append(gpsLocationData.getHeight()).append(splitStr)
                    .append(gpsLocationData.getDirection()).append(splitStr)
                    .append(gpsLocationData.getSpeed()).append(splitStr)
                    .append(gpsLocationData.getAlarm()).append(splitStr)
                    .append(gpsLocationData.getStatus()).append(splitStr)
                    .append(JSON.toJSON(getFaultInfoList(faultInfo.getFaultListDataList()))).append(splitStr)
                    .append(faultInfo.getOriginalLat()).append(splitStr)
                    .append(faultInfo.getOriginalLng()).append(splitStr)
                    .append(faultInfo.getMark()).append(splitStr)
                    //添加字段只能在分割线之上添加
                    //------------------------------------------分割线----------------------------------------
                    .append(DateUtils.format(gpsLocationData.getGpsTime() * 1000, "yyyyMMdd"));

            //将0F39报文拼接后写入hdfs
            this.out.write(faultInfoStr.toString().getBytes(Charsets.UTF_8));
            if (this.appendNewline) {
                this.out.write(10);
            }
        } catch (Exception e) {
            logger.error("执行HDFS的FaultInfo拦截器失败：" + e.getMessage(), e);
        }
    }

    public List<FaultInfoDto> getFaultInfoList(List<LCFaultInfo.FaultListData> faultListData) {
        if (faultListData == null) {
            return Collections.emptyList();
        }
        List<FaultInfoDto> faultInfoDtos = new ArrayList<>();
        for (LCFaultInfo.FaultListData faultInfo : faultListData) {
            faultInfoDtos.add(FaultInfoDto.protoToBean(faultInfo));
        }
        return faultInfoDtos;
    }

    public static class Builder implements EventSerializer.Builder {
        public Builder() {
        }

        public EventSerializer build(Context context, OutputStream out) {
            return new HDFSFaultInfoSerializer(out, context);
        }
    }
}
